<template>
  <div clsss="edit-info">
    <el-dialog
      v-model="dialogVisible"
      :title="titleInfo"
      width="50%"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        ref="listQueryRef"
        :rules="listQueryRules"
        :model="listQuery"
        label-width="120"
        :inline="true"
      >
        <el-form-item label="公司名称" prop="company_id">
          <el-select
            class="!w-[300px]"
            clearable
            v-model="listQuery.company_id"
            placeholder="请选择公司名称"
          >
            <el-option
              v-for="(item, index) in companyIdList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="贷款金额(万元)
        "
          prop="loan_money"
        >
          <el-input
            class="!w-[300px]"
            maxlength="10"
            v-model="listQuery.loan_money"
            placeholder="请输入贷款金额
        "
            autocomplete="off"
            clearable
            @input="
              listQuery.loan_money = listQuery.loan_money
                .replace(/[^0-9.]/g, '')
                .replace(/\.{2,}/g, '.')
                .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
            "
          />
        </el-form-item>
        <el-form-item
          label="利率(%)
        "
          prop="interest_rate"
        >
          <el-input
            class="!w-[300px]"
            v-model="listQuery.interest_rate"
            maxlength="3"
            placeholder="请输入利率
        "
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item label="贷款类型" prop="type_id">
          <el-select
            v-model="listQuery.type_id"
            placeholder="请选择贷款类型"
            class="select-info"
            clearable
          >
            <el-option
              v-for="item in typeIdList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款开始时间" prop="loan_start">
          <el-date-picker
            style="width: 300px"
            v-model="listQuery.loan_start"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择企业成立时间"
          />
        </el-form-item>
        <el-form-item label="贷款结束时间" prop="loan_over">
          <el-date-picker
            style="width: 300px"
            v-model="listQuery.loan_over"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择企业成立时间"
          />
        </el-form-item>
        <el-form-item
          label="法人代表
      "
          prop="legal_id"
        >
          <el-select
            clearable
            class="select-box"
            v-model="listQuery.legal_id"
            placeholder="请选择法人代表"
          >
            <el-option
              v-for="item in legalList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款管理员ID">
          <el-select
            class="!w-[300px]"
            clearable
            v-model="listQuery.staff_id"
            placeholder="请选择公司名称"
          >
            <el-option
              v-for="(item, index) in companyIdList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款期限(月)" prop="loan_month">
          <el-input
            placeholder="请输入内容"
            oninput="listQuery.loan_month=listQuery.loan_month.replace(/[^\d]/g,'')"
            v-model="listQuery.loan_month"
            clearable
            class="!w-[300px]"
          />
        </el-form-item>
        <el-form-item label="抵押物">
          <el-select
            v-model="listQuery.collateral_id"
            clearable
            placeholder="请选择抵押物"
            class="!w-[300px]"
          >
            <el-option
              v-for="item in collateralList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="担保人">
          <el-select
            v-model="listQuery.security_user"
            clearable
            placeholder="请选择担保人"
            class="!w-[300px]"
          >
            <el-option
              v-for="item in securityUserList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="贷款银行
        "
          prop="register_fund"
        >
          <el-input
            class="!w-[300px]"
            v-model="listQuery.loan_bank"
            placeholder="请输入贷款银行
        "
            autocomplete="off"
            clearable
          />
        </el-form-item>
        <el-form-item label="担保公司">
          <el-select
            clearable
            v-model="listQuery.security_company"
            placeholder="请选择公司名称"
          >
            <el-option
              v-for="(item, index) in companyIdList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="每月还款日期">
          <el-date-picker
            style="width: 300px"
            v-model="listQuery.loan_due"
            type="date"
            maxlength="3"
            class="!w-[300px]"
            value-format="YYYY-MM-DD"
            placeholder="请选择每月还款日期"
          />
        </el-form-item>
        <el-form-item label="授托公司">
          <el-select
            class="!w-[300px]"
            clearable
            v-model="listQuery.entrusting_id"
            placeholder="请选择授托公司"
          >
            <el-option
              v-for="(item, index) in companyIdList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="使用单位">
          <el-input
            class="!w-[300px]"
            placeholder="请输入使用单位"
            v-model="listQuery.building_user"
            clearable
          />
        </el-form-item> -->
        <el-form-item label="是否最高额">
          <el-select
            v-model="listQuery.maximum_amount"
            placeholder="请选择是否最高额"
            class="!w-[300px]"
          >
            <el-option
              v-for="item in maximumAmountlist"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="可用贷款余额">
          <el-input
            class="!w-[300px]"
            placeholder="请输入贷款余额"
            @input="
              listQuery.usable_balance = listQuery.usable_balance.replace(
                /[^\d]/g,
                ''
              )
            "
            v-model="listQuery.usable_balance"
            clearable
          />
        </el-form-item>
        <el-form-item label="授信额度">
          <el-input
            class="!w-[300px]"
            placeholder="请输入授信额度"
            @input="
              listQuery.credit_limit = listQuery.credit_limit.replace(
                /[^\d]/g,
                ''
              )
            "
            v-model="listQuery.credit_limit"
            clearable
          />
        </el-form-item>
        <el-form-item label="用信额度">
          <el-input
            class="!w-[300px]"
            placeholder="请输入用信额度"
            @input="
              listQuery.use_limit = listQuery.use_limit.replace(/[^\d]/g, '')
            "
            v-model="listQuery.use_limit"
            clearable
          />
        </el-form-item>
        <el-form-item label="授信余额">
          <el-input
            class="!w-[300px]"
            placeholder="请输入授信余额"
            @input="
              listQuery.credit_balance = listQuery.credit_balance.replace(
                /[^\d]/g,
                ''
              )
            "
            v-model="listQuery.credit_balance"
            clearable
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            class="!w-[300px]"
            placeholder="请输入备注"
            v-model="listQuery.notes"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" prop="tax_level">
          <el-select
            clearable
            class="select-box"
            v-model="listQuery.status"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in statusList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="图片">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :limit="1"
              :action="actionUrl"
              accept=".png,.jpe,.jpeg"
              :data="additionalData"
              :before-upload="handleBeforeUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                prop="imageUrl"
              />
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" type="danger">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { getSessionKey } from "@/utils/auth";
import {
  peopleSelect,
  companySelect,
  selectType,
  collateralSelect,
  securitySelect,
  useunitSelect
} from "@/api/companyList";
import { getuFile } from "@/api/user";
const imageUrl = ref(
  "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
);

import {
  reactive,
  ref,
  inject,
  onMounted,
  defineProps,
  defineEmits,
  nextTick,
  defineExpose,
  watch
} from "vue";
const listQueryRef = ref("");
const dataObj = ref({});
const titleText = ref("");
const companyIdList = ref([]);
const loading = ref("");
const typeIdList = ref([]);
const collateralList = ref([]);
const securityUserList = ref([]);
const useIdList = ref([]);
const maximumAmountlist = ref([
  {
    label: "是",
    value: 1
  },
  {
    label: "否",
    value: 2
  }
]);
const statusList = ref([
  {
    name: "待还款",
    id: 1
  },
  {
    name: "已还款",
    id: 2
  },
  {
    name: "已逾期",
    id: 3
  }
]);
const listQuery = ref({});
const taxLevelList = ref([
  {
    name: "小规模",
    id: 1
  },
  {
    name: "一般纳税人",
    id: 2
  }
]);

const additionalData = reactive({
  // 这里添加你需要传递的额外参数
  type: "admin",
  action: "loan"
});
onMounted(() => {
  getList();
  getCompanySelect();
  getSelectType();
  init();
  getUseunitSelect();
  // remoteMethod();
});
//使用单位列表
const getUseunitSelect = () => {
  useunitSelect().then(res => {
    if (res.code == 200) {
      useIdList.value = res.data;
    }
  });
};
const init = () => {
  // 抵押物列表
  const params = {
    collateral: ""
  };
  collateralSelect(params).then(res => {
    if (res.code == 200) {
      collateralList.value = res.data;
    }
  });
  getSecuritySelect();
};
// 担保人列表
const getSecuritySelect = () => {
  const params = {
    name: ""
  };
  securitySelect(params).then(res => {
    if (res.code == 200) {
      securityUserList.value = res.data;
    }
  });
};
// 公司列表

// 上传图片
const handleBeforeUpload = file => {
  const filesInfo = file.size / 1024 / 1024 < 2;
  if (!filesInfo) {
    ElMessageBox.alert("上传头像图片大小不能超过 2MB!");
  }
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      // 转换成功，得到Base64字符串
      const base64 = e.target.result;
      // 处理Base64字符串，例如可以在这里发起接口请求
      const params = {
        ...additionalData,
        file: base64
      };
      getuFile(params).then(res => {
        if (res.code == 200) {
          imageUrl.value = base64;
          listQuery.value.image = res.data;
        }
      });
    };
    reader.onerror = reject;
    reader.readAsDataURL(file); // 转换文件为Base64
  });
};

// 贷款类型下拉框
const getSelectType = async () => {
  try {
    const params = {
      name: ""
    };
    const res = await selectType(params);
    console.log(res, "====---");
    typeIdList.value = res.data;
  } catch (err) {}
};
const remoteMethod = query => {
  console.log("输入的", query);
  if (query !== "") {
    loading.value = true;
    const parmas = {
      name: query,
      admin_id: 1
    };
    companySelect(parmas).then(res => {
      if (res.code == 200) {
        companyIdList.value = res.data.map(el => {
          el.id = Number(el.id);
          return el;
        });
      } else {
      }
    });
  } else {
    this.getCompanySelect();
  }
};
// 获取公司
const getCompanySelect = () => {
  const parmas = {
    name: "",
    admin_id: 1
  };
  companySelect(parmas).then(res => {
    if (res.code == 200) {
      companyIdList.value = res.data.map(el => {
        el.id = Number(el.id);
        return el;
      });
    }
  });
};
const dialogVisible = ref(false);
const opneDialogVisible = data => {
  if (props.isEdit == "1") {
    listQuery.value = { ...data };
    listQuery.value.collateral_id = Number(data.collateral_id);
    listQuery.value.security_user = Number(data.security_user);
    listQuery.value.security_company = Number(data.security_company);
    console.log(data, "======");
  }
  dialogVisible.value = true;
};

const getList = async () => {
  const obj = {
    name: ""
  };
  const res = await peopleSelect(obj);
  if (res.code == 200) {
    const dataList = res.data;
    legalList.value = dataList;
  }
};
const legalList = ref([]);
const listQueryRules = {
  company_id: [{ required: true, message: "请选择公司名称", trigger: "blur" }],
  loan_money: [{ required: true, message: "请输入贷款银行", trigger: "blur" }],
  interest_rate: [{ required: true, message: "请输入利率", trigger: "blur" }],
  loan_year: [{ required: true, message: "请输入贷款年限", trigger: "blur" }],
  loan_start: [
    { required: true, message: "请选择贷款开始时间", trigger: "blur" }
  ],
  type_id: [{ required: true, message: "请选择贷款类型", trigger: "blur" }],
  legal_id: [{ required: true, message: "请选择法人代表", trigger: "blur" }],
  loan_month: [
    { required: true, message: "请输入贷款期限(月)", trigger: "blur" }
  ]
};
const props = defineProps({
  titleInfo: {
    type: String,
    default: ""
  },
  isEdit: {
    type: String,
    default: ""
  }
});
const handleClose = () => {
  imageUrl.value = "";
  listQuery.value.image = "";
  listQueryRef.value.resetFields(); // 清除表单校验以及表单数据初始化
  dialogVisible.value = false;
};
const disabledDate = time => {
  return time.getTime() > Date.now();
};
const emit = defineEmits(["handleSubmit"]);
const handleSubmit = () => {
  listQueryRef.value.validate(valid => {
    if (valid) {
      // 添加
      const parmas = listQuery.value;
      // parmas.admin_id = getSessionKey().admin_id;
      emit("handleSubmit", parmas);
    }
  });
};
defineExpose({ opneDialogVisible }); //子组件需要把数据导出去
</script>

<style lang="scss" scoped>
.select-box {
  width: 300px;
}

.select-info {
  width: 300px;
}

.label-info {
  color: #333;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
